﻿using BaseSimpleDao;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Text;

namespace AMInstantMessagingDao
{
    public class SimpleCache
    {
        private SimpleCache()
        {
            _ConnectionMultiplexer = ConnectionMultiplexer.Connect("127.0.0.1:6379");
        }

        protected ConnectionMultiplexer _ConnectionMultiplexer = null;

        public ConnectionMultiplexer ConnectionMultiplexer { get { return _ConnectionMultiplexer; } }

        private static SimpleCache _SimpleCache = new SimpleCache();

        public static SimpleCache GetInstance() { return _SimpleCache; }

        public string GetCacheKey(string scene, object name)
        {
            return string.Join("::", new[] { scene, name });
        }

        /// <summary>
        /// 缓存实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        public void CacheModel<T>(T model)
            where T : BaseModel
        {
            if (model == null)
                return;

            var type = typeof(T);
            string cache_key = GetCacheKey(type.FullName, model.Id);
            _ConnectionMultiplexer.GetDatabase().StringSet(cache_key, JsonConvert.SerializeObject(model));
        }

        /// <summary>
        /// 获取之前缓存的实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        public T GetCacheModel<T>(long id)
            where T : BaseModel
        {
            var type = typeof(T);
            string cache_key = GetCacheKey(type.FullName, id);
            var value = _ConnectionMultiplexer.GetDatabase().StringGet(cache_key);

            if (value.IsNull)
                return default(T);

            return JsonConvert.DeserializeObject<T>(value);
        }
    }
}
